package com.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @auther: zhangxin
 * @Description: springmvc组件定制类
 */
@Configuration
// 开启SpringMVC定制配置功能
@EnableWebMvc   //相当于配置了<mvc:annotation-driven />
public class WebMvcConfiguration implements WebMvcConfigurer {

    // 添加视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // 配置内部资源视图
//        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//        viewResolver.setPrefix("/");
//        viewResolver.setSuffix(".jsp");
//
//        // 注册视图
//        registry.viewResolver(viewResolver);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 配置java.util.Date
        DateFormatter dateFormatter = new DateFormatter();
        dateFormatter.setPattern("yyyy-MM-dd HH:mm:ss");
        registry.addFormatter(dateFormatter);


        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setTimeFormatter(DateTimeFormatter.ofPattern("HH:mm:ss"));
        registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        registrar.registerFormatters(registry);
    }

    @Bean
    public MethodValidationPostProcessor validationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    @Override
    public Validator getValidator() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        // 读取配置文件的编码格式
        messageSource.setDefaultEncoding("utf-8");
        // 缓存时间，-1表示不过期
        messageSource.setCacheMillis(-1);
        // 配置文件前缀名，设置为Messages,那你的配置文件必须以Messages.properties/Message_en.properties...
        messageSource.setBasename("classpath:ValidatedMessages");

        // 校验器工厂对象
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        // 可以不设置，默认会自动查找校验实现类
        factoryBean.setProviderClass(HibernateValidator.class);
        // 消息源
        factoryBean.setValidationMessageSource(messageSource);
        return factoryBean;
    }

    // Servlet3多部分数据解析工具
    @Bean
    public MultipartResolver multipartResolver(){
        return new StandardServletMultipartResolver();
    }

    // 配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns配置拦截的请求，excludePathPatterns配置放行的请求
        // registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/users/*");
        // 所有的请求都进入拦截器
        // registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
    }

    // 执行时还没有注册任何HttpMessageConverter
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    }

    // 在系统默认注册完成后，才会在这里注册HttpMessageConverter
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 为了演示注册效果，这里先清除所有默认注册的HttpMessageConverter
//        converters.clear();

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.setDateFormat(sdf);
//        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
//        //通过设置索引,让自己的转换器放在最前面,否则默认的jackson转换器会在前面,用不上我们设置的转换器.
//        converters.add(0, converter);


        for (HttpMessageConverter converter : converters) {
            if (converter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
                if (converter instanceof MappingJackson2HttpMessageConverter) {
                    ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();

                SimpleModule module = new SimpleModule();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(dateTimeFormatter));
                module.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(dateTimeFormatter));
                objectMapper.registerModule(module);
                module = new SimpleModule();
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                module.addSerializer(LocalDate.class,new LocalDateSerializer(dateFormatter));
                module.addDeserializer(LocalDate.class,new LocalDateDeserializer(dateFormatter));
                objectMapper.registerModule(module);
            }
        }

    }


}
